package cn.mybatishelper.common;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

/**
 * 文件处理工具类
 *
 * @author GameKing
 */
public abstract class MybatisFileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(MybatisFileUtil.class);

    /**
     * 根据传入的参数生成文件和文件夹
     *
     * @param fileContent 要生成的文件内容
     * @param classPath   buildpath路径，即从工程目录到源文件夹路径
     * @param fileUrl     文件路径
     * @param objName     文件名
     */
    public static void createFile(String fileContent, String classPath, String fileUrl, String objName) {
        OutputStreamWriter writer = null;
        try {
            String fileUri = fileUrl.replaceAll("\\.", "/");

            File file = new File(classPath + "/" + fileUri);
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }
            file = new File(classPath + "/" + fileUri + "/" + objName);
            if (!file.exists()) {
                file.createNewFile();
            }
            writer = new OutputStreamWriter(new FileOutputStream(file));
            writer.write(fileContent);
        } catch (Exception e) {
            LOGGER.error(objName + "文件生成出错...", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

}
